package com.avic.rong.userOrder;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.avic.rong.R;
import com.avic.rong.utils.BitmapUtils;
import com.avic.rong.utils.LocalStorageUtil;
import com.avic.rong.utils.OnClickLimitListener;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.DeviceInfoUtil;

import java.io.File;
import java.io.IOException;

/**
 * 拍照、相册选取
 * Created by 小铁匠 on 2017/12/14.
 */

public class DialogPhotoSelect {
    private final int REQUEST_CODE_TO_CAMEAR = 1001;
    private final int REQUEST_CODE_TO_PHOTOS = 1010;
    private Activity mActivity;
    private AlertDialog dialog;
    private PhotoSelectCallBack photoSelectCallBack;

    /**
     * 图片选择回调
     */
    public interface PhotoSelectCallBack {
        void photoSelectFinish(String path);
    }

    public DialogPhotoSelect(Activity activity, PhotoSelectCallBack callBack) {
        this.mActivity = activity;
        this.photoSelectCallBack = callBack;
    }

    public void showDialog() {
        dialog = generateLoginDialog();
        dialog.show();
        setDialoglayout();
        setDialogContentView();
    }

    private AlertDialog generateLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        return builder.create();
    }

    private void setDialoglayout() {

        WindowManager windowManager = mActivity.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();

        lp.width = (int) (display.getWidth() - DeviceInfoUtil.dip2px(mActivity, 80)); // 设置宽度
        lp.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
        // lp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
        lp.dimAmount = 0.5f;
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.getWindow().setAttributes(lp);
        dialog.getWindow().setWindowAnimations(R.style.DialogStyle);
    }

    private void setDialogContentView() {

        View view = View.inflate(mActivity, R.layout.dialog_select_photo, null);

        TextView tvCamera = view.findViewById(R.id.tv_camera);
        TextView tvPhoto = view.findViewById(R.id.tv_photo);


        tvCamera.setOnClickListener(new OnClickLimitListener() {
            @Override
            public void onClickLimit(View v) {
                dialogDismiss();
                selectPhotoFromCamera();
            }
        });

        tvPhoto.setOnClickListener(new OnClickLimitListener() {

            @Override
            public void onClickLimit(View v) {
                dialogDismiss();
                selectPhotoFromPhotos();
            }
        });

        dialog.getWindow().setContentView(view);
    }

    /**
     * 通过拍照获取
     */
    private void selectPhotoFromCamera() {
        File basePath = new File(LocalStorageUtil.getInstance(mActivity).getSdcardAbsolutePath());
        try {
            if (!basePath.exists()) {
                basePath.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        LocalStorageUtil.getInstance(mActivity).setUploadUserPhotoTempFilePath(LocalStorageUtil.getInstance(mActivity).getSdcardAbsolutePath()+ File.separator + System.currentTimeMillis()+"unhandled.jpg");
        File newfile = new File(LocalStorageUtil.getInstance(mActivity).getUploadUserPhotoTempFilePath());// Global.UPLOAD_USER_PHOTO_TEMP_FILE_PATH
        try {
            newfile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(mActivity,"com.avic.rong.provider",newfile));
        }else{
            Uri outputFileUri = Uri.fromFile(newfile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        }

        //去寻找是否已经有了相机的权限
        if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){

            //Toast.makeText(Main3Activity.this,"您申请了动态权限",Toast.LENGTH_SHORT).show();
            //如果有了相机的权限有调用相机
            mActivity.startActivityForResult(cameraIntent, REQUEST_CODE_TO_CAMEAR);

        }else{
            //否则去请求相机权限
            ActivityCompat.requestPermissions(mActivity,new String[]{Manifest.permission.CAMERA},100);

        }



    }

    /**
     * 从相册获取
     */
    private void selectPhotoFromPhotos() {
        try {
            Intent pickPhoto = new Intent(Intent.ACTION_PICK, null);
            pickPhoto.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            mActivity.startActivityForResult(pickPhoto, REQUEST_CODE_TO_PHOTOS);
        } catch (Exception e) {
            e.printStackTrace();
            ToastTools.showToast(mActivity, "手机上未安装图库");
        }
    }



    public void onActivityReuslt(int requestCode, int resultCode, Intent data) {

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_TO_CAMEAR:
                    if (photoSelectCallBack != null) {
                        photoSelectCallBack.photoSelectFinish(LocalStorageUtil.getInstance(mActivity).getUploadUserPhotoTempFilePath());
                    }
                    break;
                case REQUEST_CODE_TO_PHOTOS:
                    try {
                        Uri uri = data.getData();
                        String img_path = "";
                        if ("content".equals(uri.getScheme())) {//本地图库
                            String[] proj = {MediaStore.Images.Media.DATA};
                            Cursor cursor = mActivity.getContentResolver().query(uri, proj, null, null, null);
                            int actual_image_column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            cursor.moveToFirst();
                            img_path = cursor.getString(actual_image_column_index);
                            cursor.close();
                        } else if ("file".equals(uri.getScheme())) {//云图库
                            img_path = uri.getPath();
                        }
                        if (photoSelectCallBack != null) {
                            photoSelectCallBack.photoSelectFinish(img_path);
                        }
                    } catch (Exception e) {
                        ToastTools.showToast(mActivity, mActivity.getString(R.string.pcikimagefrom_system_album));
                    }
                    break;
            }
        }

    }

    /**
     * 保存图片
     * @param imgPath
     * @param saveImgPath
     */
    private void reloadPhoto(String imgPath, final String saveImgPath) {
      /*  ImageLoader.reLoadSizeImageBitmap(mActivity, "file://" + imgPath, DeviceInfoUtil.getScreenWidth(mActivity), DeviceInfoUtil.getScreenHeightWithoutStatusBar(mActivity), new BaseBitmapDataSubscriber() {
            @Override
            protected void onNewResultImpl(final Bitmap bitmap) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        generateUploadUserPhotoToLocal(saveImgPath, bitmap);
                    }
                });
            }

            @Override
            protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {

            }
        });*/


    }

    private void generateUploadUserPhotoToLocal(String saveImgPath, Bitmap finalBitmap) {
        BitmapUtils.saveBitmapToLocalFile(saveImgPath, finalBitmap, 50, false);// Global.UPLOAD_USER_PHOTO_CLIPED_FILE_PATH
        if (finalBitmap != null && !finalBitmap.isRecycled()) {
            finalBitmap.recycle();
            finalBitmap = null;
        }
        if (photoSelectCallBack != null) {
            photoSelectCallBack.photoSelectFinish(saveImgPath);
        }
    }

    public void dialogDismiss() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            dialog = null;
        }
    }

    public boolean isShowing() {
        if (dialog == null)
            return false;
        return dialog.isShowing();
    }


}
